/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package project1;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static project1.Project1.conn;
/**
 *
 * @author haihip
 */
public class SqlFunc {
    private Connection connection= null;
    private Statement stmt = null;
    
    /*public SqlFunc(String database)
    {
        try {  
            connection = DriverManager.getConnection("jdbc:sqlite:"+database);
        } catch (SQLException ex) {
            Logger.getLogger(SqlFunc.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public SqlFunc(Connection c)
    {
        connection =c;
    }*/
    public SqlFunc()
    {
        connection = conn;
    }
    public void closeConnection()
    {
        try {
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(SqlFunc.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public ResultSet select(String query)
    {
        ResultSet ret = null;
        try {
            Class.forName("org.sqlite.JDBC");
            connection.setAutoCommit(false);
            stmt = connection.createStatement();
            ret = stmt.executeQuery(query);
            //stmt.close();
        }
        catch(ClassNotFoundException | SQLException e)
        {
            System.out.println("Error select SQL");        
        }
        return ret;
    }
    
    public boolean query(String query)
    {
        try {
            Class.forName("org.sqlite.JDBC");
            connection.setAutoCommit(false);
            stmt = connection.createStatement();
            stmt.executeUpdate(query);
            connection.commit();
            return true;
        }
        catch(ClassNotFoundException | SQLException e)
        {
            System.out.println("Error query SQL");
        }
        return false;
    }
    
    public int numrows(String query)
    {
        int dem=0;
        ResultSet ret = select(query);
        try {
            while(ret.next())
            {
                dem++;
            }
        } catch (SQLException ex) {
            Logger.getLogger(SqlFunc.class.getName()).log(Level.SEVERE, null, ex);
        }
        resultClose(ret);
        return dem;
    }
    public void resultClose(ResultSet ret)
    {
        try {
            if(!ret.isClosed())
                ret.close();
        } catch (SQLException ex) {
            Logger.getLogger(SqlFunc.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
